import React, { PureComponent } from 'react';
import { connect } from 'dva';
// import { routerRedux } from 'dva/router';
import {
  Card,
  // Alert,
  Button,
  // Tooltip,
  Form,
  Row,
  Col,
  Select,
  Input,
  TreeSelect,
  InputNumber,
  Spin,
  BackTop,
  // Divider,
  notification,
  message,
} from 'antd';
import PageHeaderWrapper from '../../../components/PageHeaderWrapper';
import CustomBrandModal from '../../CustomBrand/OperateModal';
import ProductTypeModal from '../../ProductType/OperateModal';
import ProductUnitModal from '../../ProductUnit/OperateModal';
import buildTree from '../../../utils/productTypeTools';

// const { TextArea } = Input;
const FormItem = Form.Item;
const { Option, OptGroup } = Select;
const InputGroup = Input.Group;

@connect(({ product, customBrand, productType, productUnit, loading }) => ({
  product,
  customBrand,
  productType,
  productUnit,
  customBrandLoading: loading.effects['customBrand/list'],
  productTypeLoading: loading.effects['productType/list'],
  productUnitLoading: loading.effects['productUnit/list'],
  loading: loading.models.product,
}))
@Form.create()
class Edit extends PureComponent {
  isMountedFlag = false;

  state = {
    addCustomBrandVisible: false,
    addProductTypeVisible: false,
    addProductUnitVisible: false,
    customBrandList: [],
    productTypeList: [],
    productTypeTreeData: [],
    productUnitList: [],
    metaData: null,
    saving: false,
  };

  componentDidMount() {
    this.isMountedFlag = true;
    const { dispatch, match } = this.props;
    const { params } = match;
    const { id: productId } = params;

    this.reloadCustomBrandData(() => {
      this.reloadProductTypeData(() => {
        this.reloadProductUnitData(() => {
          dispatch({
            type: 'product/get',
            payload: {
              productId,
            },
          }).then(() => {
            if (this.isMountedFlag) {
              const {
                product: { data },
              } = this.props;

              this.setState({ metaData: data });
            }
          });
        });
      });
    });
  }

  componentWillUnmount() {
    this.isMountedFlag = false;
  }

  reloadCustomBrandData = callback => {
    const { dispatch } = this.props;
    dispatch({
      type: 'customBrand/list',
      payload: { pageNo: 1, pageSize: 100, status: 2 },
    }).then(() => {
      const {
        customBrand: {
          data: { list },
        },
      } = this.props;

      this.setState({ customBrandList: list });

      if (typeof callback === 'function') {
        callback();
      }
    });
  };

  reloadProductTypeData = callback => {
    const { dispatch } = this.props;
    dispatch({
      type: 'productType/list',
      payload: { pageNo: 1, pageSize: 100, status: 2 },
    }).then(() => {
      const {
        productType: {
          data: { list },
        },
      } = this.props;

      const treeDataAll = buildTree(list, false, null, true);
      this.setState({ productTypeList: list });
      this.setState({ productTypeTreeData: treeDataAll });

      if (typeof callback === 'function') {
        callback();
      }
    });
  };

  reloadProductUnitData = callback => {
    const { dispatch } = this.props;
    dispatch({
      type: 'productUnit/list',
      payload: { pageNo: 1, pageSize: 100, status: 2 },
    }).then(() => {
      const {
        productUnit: {
          data: { list },
        },
      } = this.props;

      this.setState({ productUnitList: list });

      if (typeof callback === 'function') {
        callback();
      }
    });
  };

  openCustomBrandModal = () => {
    this.setState({
      addCustomBrandVisible: true,
    });
  };

  openProductTypeModal = () => {
    this.setState({
      addProductTypeVisible: true,
    });
  };

  openProductUnitModal = () => {
    this.setState({
      addProductUnitVisible: true,
    });
  };

  afterAddCustomBrandModalOk = data => {
    const { form } = this.props;

    const { status, message: messageText } = data;
    if (status === 200) {
      message.success('添加品牌成功，已自动选定！');
      const {
        data: { customBrandId: customBrandIdNew },
      } = data;

      this.reloadCustomBrandData(() => {
        form.setFieldsValue({
          customBrandId: `${customBrandIdNew}`,
        });
      });
    } else {
      message.success(messageText);
    }

    this.setState({
      addCustomBrandVisible: false,
    });
  };

  afterAddProductTypeModalOk = data => {
    const { form } = this.props;

    const { status, message: messageText } = data;
    if (status === 200) {
      message.success('添加分类成功，已自动选定！');
      const {
        data: { productTypeId: productTypeIdNew },
      } = data;

      this.reloadProductTypeData(() => {
        form.setFieldsValue({
          productTypeId: `${productTypeIdNew}`,
        });
      });
    } else {
      message.success(messageText);
    }

    this.setState({
      addProductTypeVisible: false,
    });
  };

  afterAddProductUnitModalOk = data => {
    // console.dir(data);
    const { form } = this.props;

    const { status, message: messageText } = data;
    if (status === 200) {
      message.success('添加计量单位成功，已自动选定！');
      const {
        data: { productUnitId: productUnitIdNew },
      } = data;

      this.reloadProductUnitData(() => {
        form.setFieldsValue({
          productUnitId: `${productUnitIdNew}`,
        });
      });
    } else {
      message.success(messageText);
    }

    this.setState({
      addProductUnitVisible: false,
    });
  };

  afterAddCustomBrandModalCancel = () => {
    this.setState({
      addCustomBrandVisible: false,
    });
  };

  afterAddProductTypeModalCancel = () => {
    this.setState({
      addProductTypeVisible: false,
    });
  };

  afterAddProductUnitModalCancel = () => {
    this.setState({
      addProductUnitVisible: false,
    });
  };

  saveData = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      // location: { pathname },
    } = this.props;
    const { metaData } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.productId = metaData.productsId;

        dispatch({
          type: 'product/update',
          payload: submitValue,
        }).then(() => {
          this.setState({ saving: false });
          const {
            product: { data },
          } = this.props;
          const { status, message: messageText } = data;
          if (status === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          } else {
            notification.error({
              placement: 'bottomRight',
              message: '操作结果',
              description: messageText,
            });
          }

          // dispatch(
          //   routerRedux.replace({
          //     pathname: `${pathname.replace('/load/', '/update/')}`,
          //   })
          // );
        });
      }
    });
  };

  render() {
    const {
      form,
      loading,
      customBrandLoading,
      productTypeLoading,
      productUnitLoading,
      dispatch,
    } = this.props;
    const {
      metaData,
      saving,
      addCustomBrandVisible,
      addProductTypeVisible,
      addProductUnitVisible,
      customBrandList,
      productTypeList,
      productTypeTreeData,
      productUnitList,
    } = this.state;
    const { getFieldDecorator } = form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };

    return (
      <PageHeaderWrapper title={`产品详情 - ${(metaData || { name: '' }).name || ''}`}>
        <Card
          title="基本信息"
          style={{ marginBottom: 24 }}
          bordered={false}
          extra={
            <Button type="primary" icon="save" onClick={this.saveData}>
              {'保存'}
            </Button>
          }
        >
          <Spin
            spinning={
              customBrandLoading || productTypeLoading || productUnitLoading || loading || saving
            }
          >
            <Form onSubmit={this.handleSubmit}>
              <Row gutter={24}>
                <Col span={12} style={{ display: 'block' }}>
                  <FormItem {...formItemLayout} label="商品名称">
                    {getFieldDecorator('name', {
                      rules: [{ required: true, message: '请输入商品名称!' }],
                      initialValue: (metaData || { name: '' }).name || '',
                    })(<Input />)}
                  </FormItem>
                </Col>
                <Col span={12} style={{ display: 'block' }}>
                  <FormItem {...formItemLayout} label="品牌">
                    <InputGroup compact>
                      {getFieldDecorator('customBrandId', {
                        rules: [{ required: false, message: '请选择品牌!' }],
                        initialValue: `${(metaData || { customBrandId: '' }).customBrandId || ''}`,
                      })(
                        <Select
                          style={{ width: '86%' }}
                          showSearch
                          allowClear
                          placeholder="请选择品牌"
                        >
                          <OptGroup label="已有品牌列表">
                            {customBrandList.map(d => (
                              <Option key={d.customBrandId} title="">
                                {d.name}
                              </Option>
                            ))}
                          </OptGroup>
                        </Select>
                      )}
                      <Button
                        style={{
                          width: '14%',
                          border: '1px solid #d9d9d9',
                          backgroundColor: '#fafafa',
                        }}
                        icon="plus"
                        title="增加新的品牌"
                        onClick={this.openCustomBrandModal}
                      />
                    </InputGroup>
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={12} style={{ display: 'block' }}>
                  <FormItem {...formItemLayout} label="商品分类">
                    <InputGroup compact>
                      {getFieldDecorator('productTypeId', {
                        rules: [{ required: true, message: '请选择商品分类!' }],
                        initialValue:
                          (metaData || { productTypeId: 0 }).productTypeId === 0
                            ? ''
                            : `${metaData.productTypeId}`,
                      })(
                        <TreeSelect
                          style={{ width: '86%' }}
                          showSearch
                          // allowClear
                          // value={productTypeIdSelect}
                          dropdownStyle={{ maxHeight: 260, overflow: 'auto' }}
                          treeData={productTypeTreeData}
                          placeholder="请选择商品分类"
                          searchPlaceholder="在这里输入文字可以搜索选项哦"
                          treeDefaultExpandAll
                        />
                      )}
                      <Button
                        style={{
                          width: '14%',
                          border: '1px solid #d9d9d9',
                          backgroundColor: '#fafafa',
                        }}
                        icon="plus"
                        title="增加新的分类"
                        onClick={this.openProductTypeModal}
                      />
                    </InputGroup>
                  </FormItem>
                </Col>
                <Col span={12} style={{ display: 'block' }}>
                  <FormItem {...formItemLayout} label="排序值">
                    {getFieldDecorator('customSort', {
                      rules: [{ required: false, message: '请输入排序值， 0 ~ 999,999 之间!' }],
                      initialValue: (metaData || { customSort: 0 }).customSort || 0,
                    })(<InputNumber min={0} style={{ width: '100%' }} />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={12} style={{ display: 'block' }}>
                  <FormItem {...formItemLayout} label="计量单位">
                    <InputGroup compact>
                      {getFieldDecorator('productUnitId', {
                        rules: [{ required: true, message: '请选择计量单位!' }],
                        initialValue: `${(metaData || { productUnitId: '' }).productUnitId || ''}`,
                      })(
                        <Select style={{ width: '86%' }} showSearch placeholder="请选择计量单位">
                          {productUnitList.map(d => (
                            <Option key={d.productUnitId} title="">
                              {d.name}
                            </Option>
                          ))}
                        </Select>
                      )}
                      <Button
                        style={{
                          width: '14%',
                          border: '1px solid #d9d9d9',
                          backgroundColor: '#fafafa',
                        }}
                        icon="plus"
                        title="增加新的计量单位"
                        onClick={this.openProductUnitModal}
                      />
                    </InputGroup>
                  </FormItem>
                </Col>
                <Col span={12} style={{ display: 'block' }}>
                  <FormItem {...formItemLayout} label="搜索关键词">
                    {getFieldDecorator('customSearchWords', {
                      rules: [{ required: false, message: '请输入排序值， 0 ~ 999,999 之间!' }],
                      initialValue: (metaData || { customSearchWords: '' }).customSearchWords || '',
                    })(<Input />)}
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Spin>
        </Card>
        <CustomBrandModal
          visible={addCustomBrandVisible}
          mode="add"
          dispatch={dispatch}
          afterOK={this.afterAddCustomBrandModalOk}
          afterCancel={this.afterAddCustomBrandModalCancel}
        />
        <ProductTypeModal
          visible={addProductTypeVisible}
          mode="add"
          treeData={productTypeList}
          // metaData={{}}
          showRoot
          canSelect
          dispatch={dispatch}
          afterOK={this.afterAddProductTypeModalOk}
          afterCancel={this.afterAddProductTypeModalCancel}
        />
        <ProductUnitModal
          visible={addProductUnitVisible}
          mode="add"
          dispatch={dispatch}
          afterOK={this.afterAddProductUnitModalOk}
          afterCancel={this.afterAddProductUnitModalCancel}
        />
        <BackTop />
      </PageHeaderWrapper>
    );
  }
}

export default Edit;
